package com.sdry.system.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdry.common.BaseController;
import com.sdry.common.TableDataInfo;
import com.sdry.exception.BizException;
import com.sdry.system.entity.*;
import com.sdry.system.service.DeptService;
import com.sdry.system.service.PositionService;
import com.sdry.system.service.RoleService;
import com.sdry.system.service.UserService;
import com.sdry.untils.ReadExcelXlsxUtil;
import com.sdry.untils.UserContext;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;


/**
 * @version: 1.0
 * @description: 用户管理
 * @author: cb
 * @create: 2020-01-13 20:18
 **/
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private DeptService deptService;

    @Resource
    private PositionService positionService;


    @Value("${file.profile}")
    private String profile;

    /**
     * 展示用户信息
     * @return
     */
    @RequestMapping(value = "/showUser")
    public String showUser(Model model) {
        //角色
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0L).select("role_id","role_name");
        List<SysRole> roleDataList = roleService.list(queryWrapper);
        model.addAttribute("roleDataList",roleDataList);


        //部门
        QueryWrapper<SysDept> queryWrapper02 = new QueryWrapper<>();
        queryWrapper02.eq("del_flag",0L).select("dept_id","dept_name");
        List<SysDept> sysDeptList = deptService.list(queryWrapper02);

        //岗位
        QueryWrapper<SysPosition> queryWrapper03 = new QueryWrapper<>();
        queryWrapper03.eq("del_flag",0L).select("post_id","post_name");
        List<SysPosition> sysPositionList = positionService.list(queryWrapper03);

        model.addAttribute("sysDeptList",sysDeptList);
        model.addAttribute("sysPositionList",sysPositionList);

        return "system/user/userList";
    }

    /**
     * 展示员工信息
     * @return
     */
    @RequestMapping(value = "/showStaff")
    public String showStaff(Model model) {

        //部门
        QueryWrapper<SysDept> queryWrapper02 = new QueryWrapper<>();
        queryWrapper02.eq("del_flag",0L).select("dept_id","dept_name");
        List<SysDept> sysDeptList = deptService.list(queryWrapper02);

        //岗位
        QueryWrapper<SysPosition> queryWrapper03 = new QueryWrapper<>();
        queryWrapper03.eq("del_flag",0L).select("post_id","post_name");
        List<SysPosition> sysPositionList = positionService.list(queryWrapper03);

        model.addAttribute("sysDeptList",sysDeptList);
        model.addAttribute("sysPositionList",sysPositionList);
        return "system/stff/staffList";
    }

    /**
     * 去修改页面
     * @return
     */
    @RequestMapping(value = "/showUpdateUser")
    @ResponseBody
    public String showUpdateUser(Model model,Long userId) {
        //用户
        SysUser sysUser = userService.getById(userId);
        //角色
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0L).select("role_id","role_name");
        List<SysRole> roleDataList = roleService.list(queryWrapper);
        //用户角色
        List<RoleUser> roleUsers =  userService.queryRoleUserByUserIdList(userId);
        //判断是否选中角色
        for (SysRole sysRole : roleDataList) {
            for (RoleUser roleUser : roleUsers) {
                if (sysRole.getRoleId().equals(roleUser.getRoleId()) ){
                    sysRole.setSelection(true);
                }
            }
        }
        sysUser.setSysRoleList(roleDataList);
        return JSONObject.fromObject(sysUser).toString();
    }


    /**
     * 在线用户
     * @param sysUser 用户对象
     * @return TableDataInfo
     */
 /*   @RequestMapping(value = "queryUserOnlineList")
    @ResponseBody
    public TableDataInfo queryUserOnlineList(SysUser sysUser) {
        Set keys = redisUtil.keys("*user_*");
        List<String> stringList = new ArrayList<>();
        for (Object key : keys) {
            String substring = key.toString().substring(5);
            stringList.add(substring);
        }
        List<SysUser> sysUsers = (List<SysUser>) userService.listByIds(stringList);
        return getDataTable(sysUsers, (long) stringList.size());
    }*/


    /**
     * 分页查询
     * @param sysUser 用户对象
     * @return TableDataInfo
     */
    @RequestMapping(value = "/queryUserPage" )
    @ResponseBody
    public TableDataInfo queryUserPage(SysUser sysUser) {
        logger.info("员工分页查询 sysUser = {} " + JSONObject.fromObject(sysUser));
        try {
            Page<SysUser> page = new Page(sysUser.getPage(),sysUser.getLimit());
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(sysUser.getRealName())) {
                queryWrapper.eq("del_flag",0L).like("real_name",sysUser.getRealName());
            }else {
                queryWrapper.eq("del_flag",0L);
            }



            IPage<SysUser> iPage = userService.page(page,queryWrapper);
            List<SysUser> sysUserList = iPage.getRecords();
            for (SysUser user : sysUserList) {
                SysDept sysDept = deptService.getById(user.getDeptId());
                if (sysDept == null) {
                    user.setDeptName(null);
                }else {
                    user.setDeptName(sysDept.getDeptName());
                }
            }
            return getDataTable(sysUserList,iPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("员工分页查询失败");
            return getDataTable(new ArrayList<>(),0L);
        }
    }

    /**
     * 修改员工
     * @param sysUser 用户对象
     * @return String
     */
    @RequestMapping(value = "updateUser")
    @ResponseBody
    public Integer updateUser(SysUser sysUser , @RequestParam("role[]") String[] role) {
        return userService.updateUser(sysUser, role);
    }

    /**
     * 添加用户
     * @param sysUser 用户对象
     * @return String
     */
    @RequestMapping(value = "addUser")
    @ResponseBody
    public Integer addUser(SysUser sysUser , String[] roleId) {
        return userService.addRole(sysUser, roleId);
    }

    /**
     * 添加员工
     * @param sysUser 用户对象
     * @return String
     */
    @RequestMapping(value = "addStaff")
    @ResponseBody
    public Integer addStaff(SysUser sysUser , @RequestParam("postId[]") String[] postId) {
        return userService.addStaff(sysUser, postId);
    }

    /**
     * 修改员工
     * @param sysUser 用户对象
     * @return String
     */
    @RequestMapping(value = "updateStaff")
    @ResponseBody
    public Integer updateStaff(SysUser sysUser , @RequestParam("postId[]") String[] postId) {
        return userService.updateStaff(sysUser, postId);
    }

    /**
     * 删除员工
     * @param userId 用户对象
     * @return String
     */
    @RequestMapping(value = "deleteUser")
    @ResponseBody
    public Integer deleteUser(Long userId) {
        return userService.deleteUser(userId);
    }

    /**
     * 修改员工
     * @param userId 用户对象
     * @return String
     */
    @RequestMapping(value = "update")
    @ResponseBody
    public boolean update(Long userId,String logOn) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLogOn(logOn);
        return userService.updateById(sysUser);
    }


    /**
     * 去员工修改页面
     * @return
     */
    @RequestMapping(value = "/showUpdateStaff")
    @ResponseBody
    public String showUpdateStaff(Long userId) {
        //用户
        SysUser sysUser = userService.getById(userId);
        //岗位员工表
        List<PostUser> postUserList = userService.queryPostUser(sysUser.getUserId());
        //部门
        QueryWrapper<SysDept> queryWrapper02 = new QueryWrapper<>();
        queryWrapper02.eq("del_flag",0L).select("dept_id","dept_name");
        List<SysDept> sysDeptList = deptService.list(queryWrapper02);
        sysUser.setSysDeptList(sysDeptList);
        //岗位
        QueryWrapper<SysPosition> queryWrapper03 = new QueryWrapper<>();
        queryWrapper03.eq("del_flag",0L).select("post_id","post_name");
        List<SysPosition> sysPositionList = positionService.list(queryWrapper03);
        //是否选中岗位
        for (SysPosition sysPosition : sysPositionList) {
            for (PostUser postUser : postUserList) {
                if (sysPosition.getPostId().equals(postUser.getPostId())){
                    sysPosition.setSelected(sysPosition.getPostId());
                }
            }
        }
        sysUser.setSysPositionList(sysPositionList);
        return JSONObject.fromObject(sysUser).toString();
    }

    /**
     * 修改密码展示页面
     * @return
     */
    @RequestMapping(value = "/showChangeUserPaw")
    public String showChangeUserPaw(Model model, HttpServletRequest request) {
        SysUser user = (SysUser) request.getSession().getAttribute("user");
        model.addAttribute("user",user);
        return "system/user/changePwd";
    }

    /**
     * 修改密码
     * @param userId 用户ID
     * @param oldPad 旧密码
     * @param newPad 新密码
     */
    @RequestMapping(value = "/changeUserPaw")
    @ResponseBody
    public Integer changeUserPaw(Long userId,String oldPad,String newPad) {
        Integer effect = userService.changeUserPaw(userId,oldPad,newPad);
        return effect;
    }

    /**
     * 个人设置
     */
    @RequestMapping(value = "/userInfo")
    public String queryUserMe(HttpServletRequest request,Model model) {
        SysUser user = userService.getById(UserContext.getSessionUserIdByServiceImpl());
        //user.setPhoto("/profile/"+user.getPhoto());
        model.addAttribute("user",user);
        return "system/person/me";
    }

    /**
     * 用户名是否存在
     */
    @RequestMapping(value = "/queryUserNameExist")
    @ResponseBody
    public boolean queryUserNameExist(String userName) {
        QueryWrapper<SysUser> queryWrapper02 = new QueryWrapper<>();
        queryWrapper02.eq("del_flag","0").eq("username",userName);
        List<SysUser> list = userService.list(queryWrapper02);
        if (list.size()>0){
           return true;
        }else {
           return false;
        }
    }


    /**
     * 上传图片
     * @param file 文件名称
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String,Object> uploadNew(@RequestParam("file") MultipartFile file) {
        // 获取原始名字
        String fileName = file.getOriginalFilename();
        // 获取后缀名
        // String suffixName = fileName.substring(fileName.lastIndexOf("."));文件重命名，防止重复
        String path = UUID.randomUUID() + fileName;
        fileName = profile + path;
        // 文件对象
        File dest = new File(fileName);
        // 判断路径是否存在，如果不存在则创建
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            // 保存到服务器中
            file.transferTo(dest);
            SysUser user = new SysUser();
            user.setUserId(UserContext.getSessionUserIdByServiceImpl());
            user.setPhoto("/profile/"+path);
            userService.updateById(user);
            return file("200","上传成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file("500","上传失败！");
    }

    /**
     * 返回是否上传成功的参数
     * @param code 是否
     * @param msg  meg
     */
    public Map<String,Object> file(String code,String msg){
        Map<String,Object> map = new HashMap(16);
        map.put("msg",msg);
        map.put("code",code);
        return map;
    }



    @RequestMapping(value = "importDataExcel")
    @ResponseBody
    public Map<String,Object> importDataExcel(MultipartFile file)
    {
        try {
            List<SysUser> dataList = getDataList(file);
            userService.importDataExcel(dataList);
        }catch (BizException e) {
            return file("500",e.getMessage());
        }catch (Exception e) {
            return file("500","上传失败");
        }
        return file("200","上传成功！");
    }


    public List<SysUser> getDataList(MultipartFile file){

        List<SysUser> dataList = new ArrayList();

        //判断Excel文件是否有内容
        boolean notNull=false;
        String filename=file.getOriginalFilename();
        if (!filename.matches("^.+\\.(?i)(xls)$") && !filename.matches("^.+\\.(?i)(xlsx)$")) {
            throw new BizException("上传文件格式不正确！");
        }
        //判断Excel文件的版本
        boolean isExcel2003=true;
        if (filename.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        Workbook wb = null;
        try {
            InputStream fis=file.getInputStream();
            if (isExcel2003) {
                wb = new HSSFWorkbook(fis);
            } else  {
                wb = new XSSFWorkbook(fis);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 总共有多少张sheet表
        int sheetnum = wb.getNumberOfSheets();
        for (int i = 0; i < sheetnum; i++) {
            Sheet sheet = wb.getSheetAt(i);
            // 表头数据
            Row namerow = sheet.getRow(0);
            // 表头数据
            Row headrow = sheet.getRow(1);
            if (null != headrow) {
                // 总行数
                int rowNum = sheet.getPhysicalNumberOfRows();
                // int rowNum = sheet.getLastRowNum();
                System.out.println(file.getName() + "共：" + rowNum + " 行！");

                // 总列数
                int colNum = headrow.getPhysicalNumberOfCells();

                // 判断工作表是否为空
                if (rowNum == 0) {
                    continue;
                }
                // 循环行
                for (int j = 1; j <= rowNum; j++) {
                    Row row = sheet.getRow(j);
                    if (null != row) {
                        SysUser sysUser = new SysUser();
                        String userName = ReadExcelXlsxUtil.getStringCellvalue(row.getCell(0));
                        String realName = ReadExcelXlsxUtil.getStringCellvalue(row.getCell(1));
                        String email = ReadExcelXlsxUtil.getStringCellvalue(row.getCell(2));
                        String phoneNumber = ReadExcelXlsxUtil.getStringCellvalue(row.getCell(3));

                        sysUser.setUsername(userName);
                        sysUser.setRealName(realName);
                        sysUser.setEmail(email);
                        sysUser.setPhoneNumber(phoneNumber);

                        dataList.add(sysUser);
                    }
                }
            }
        }

        return dataList;
    }
}
